/**
 * Copyright Marvell Inc
 */

package com.hisense.settings.channel;

import com.android.settings.R;
import com.hisense.settings.MyLog;
import com.hisense.settings.base.TVBaseDialog;
import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.WidgetManager;
import com.hisense.settings.util.Wrapper;
import com.hisense.settings.widget.ToastCreator;
/*import com.marvell.willowtv.framework.features.LiveTv;
import com.marvell.willowtv.framework.features.Tuner;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.interfaces.IScanEventListener;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelSearchType;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ScanStatus;
import com.marvell.willowtv.framework.util.atsc.ErrorCodes;
import com.marvell.willowtv.framework.util.atsc.InputSourceType;*/

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
import android.widget.TextView;


/**
 * This class creates the UI and initiates the Auto scanning mechanism.
 * 
 * @author Marvell
 */
public class AutoScanActivity extends TVBaseDialog /*implements IScanEventListener*/{
	private static final String TAG = "AutoScanActivity";
	
    // scan complete percentage.
    private static final int SCAN_COMPLETE_PERCENT = 100;

    // digital scan complete percentage.
    private static final int SCAN_HALF_PERCENT = 50;

    // cable digital frequency for channel number '1'
    private final String CABLE_DIGITAL_FREQ = "73.75";

    // cable analog frequency for channel number '1'
    private final String CABLE_ANALOG_FREQ = "73.7536";// "72.0036";

    // antenna digital frequency for channel number '2'
    private final String ANTENNA_DIGITAL_FREQ = "57.0";

    // Holds the application context
    private Context mContext;

    // Holds the instance of Tuner framework class
    //private Tuner mTuner;

    // Holds the number analog channel scanned
    private int mNumAnalogChannel = 0;

    // Holds the number digital channel scanned
    private int mNumDigitalChannel = 0;

    // Holds the Tuner Mode Object
    //private InputSourceType mTunerMode;

    //flag for delete favorite channels
    private int tunerMode = 1;
    // Holds the activity resources.
    private Resources mRes;

    // variable specifying whether the scanning is in progress or not
    private Handler mScanHandler = new Handler();

    // textview to hold scan type DIGITAL / ANANLOG
    private TextView mHeaderTextView;

    // textview to hold scan status text
    private TextView mScanStatus_tv1;
    private TextView mScanStatus_tv2;
    private TextView mScanStatus_tv3;
    private TextView mScanStatus_tv4;
	private TextView mTips_tv;

    // textview to hold scan progress percentage
    private TextView mProgressTextView;
    private ProgressBar mProgressBar;
    private ProgressDialog mDialog;

    private int POWER_KEY;
    private Runnable mRunnable2 = null;
        
    //private static final LiveTv mLiveTv =  TvFramework.getInstance().getLiveTvInstance();
    //lca  public final USDTVBaseUtility mBaseUtility = USDTVBaseUtility.getUSDTVBaseUtilityInstance();
    public static final String EXTRA_LAUNCH_FROM_OOBE = "launch_oobe";
    private boolean isOOBE = false;
    private boolean scanFinished = false;
    
    /**
     * Called on the creation of the activity
     * 
     * @param savedInstanceState of type Bundle
     */
    @Override
    public void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        AutoScanActivity.this.setFinishOnTouchOutside(false);
        /********************  Initialize variables    ******************/
        mContext = getApplicationContext();
        Wrapper.getWrapperInstance().setContext(mContext);
        mRes = getResources();
        POWER_KEY = mRes.getInteger(R.integer.key_power);
        mScanHandler = new Handler();
        
        //mTuner = TvFramework.getInstance().getTunerInstance();

        //mTunerMode = mTuner.getTunerMode(mContext);
        //MyLog.d(TAG, "mTunerMode:"+mTunerMode);

        setContentView(R.layout.auto_scan);
        setTimeOut(0); // no timeout during scanning
        
        mHeaderTextView = (TextView) findViewById(R.id.headertext);
        mScanStatus_tv1 = (TextView) findViewById(R.id.scanstatus_tv1);
        mScanStatus_tv2 = (TextView) findViewById(R.id.scanstatus_tv2);
        mScanStatus_tv3 = (TextView) findViewById(R.id.scanstatus_tv3);
        mScanStatus_tv4 = (TextView) findViewById(R.id.scanstatus_tv4);
        mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
        mProgressTextView = (TextView) findViewById(R.id.progressview);
	    mTips_tv=(TextView)findViewById(R.id.tipsview);
		
        mNumAnalogChannel = 0;
        mNumDigitalChannel = 0;

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isOOBE = bundle.getBoolean(EXTRA_LAUNCH_FROM_OOBE);
        }

        /******************** Start Scan ******************/
        /*if (mTunerMode == InputSourceType.CABLE_INPUT) {
            updateScanStatusText(1, CABLE_DIGITAL_FREQ, mNumAnalogChannel, mNumDigitalChannel, 0);
            tunerMode=3;
            mTips_tv.setText(R.string.cable_mode_tips);
        } else {
            updateScanStatusText(2, ANTENNA_DIGITAL_FREQ, mNumAnalogChannel, mNumDigitalChannel, 0);
            tunerMode=2;
            mTips_tv.setText(R.string.air_mode_tips);
        }*/
                
        //Setting OFF the ClosedCaption before AutoScan, to avoid any CC residue on the window
        Wrapper.getWrapperInstance().pauseCC();
        
        startScan();
        
        //clearfavoritedata();
        
        /******************** Test code for Emulator    ******************/
        /*if (TvFramework.getInstance().isPrototyping()) {
	        mRunnable2 = new Runnable() {
	            int progress = 0;
	            int chNum = 0;
	            int numOfServices = 0;
	            int curFrequency = 0;
	            int searchType = 2;
	            int searchMessage = 0;
	            
	            @Override
	            public void run() {
	                scanStatusUpdate(progress++, chNum, numOfServices, curFrequency, searchType, searchMessage);
	                if(progress <= 100) {
	                    mScanHandler.postDelayed(mRunnable2, 250);
	                    
	                    if (progress == 100)
	                        searchMessage = ScanStatus.SCAN_FINISHED.ordinal();
	                } else {
	                    return;
	                }
	            } 
	            
	        };
	        mScanHandler.postDelayed(mRunnable2, 250);
        }*/
    }

    /**
     * Called when you are no longer visible to the user. You will next receive
     * either onRestart(), onDestroy(), or nothing, depending on later user
     * activity.
     */
    @Override
    protected void onStop() {
        super.onStop();
        MyLog.d(TAG, "onStop()");

        /*final int rtnValue = mTuner.stopScan();
        if (rtnValue == ErrorCodes.FAILURE) {
        	MyLog.d(TAG, "Stopping Auto Scan Failed");
        } else if (rtnValue == ErrorCodes.SUCCESS) {
        	MyLog.d(TAG, "Stopping Auto scan SUCCESSED");
        } else {
        	MyLog.d(TAG, "Unknown");
        }*/

        // Starting the CC ON if it was previously running
        Wrapper.getWrapperInstance().resumeCC();

        stopTimeOut();
        
        cleanup();
    }

    /**
     * Override method called when activity gets closed
     */
    @Override
    protected void onDestroy() {
    	MyLog.d(TAG, "onDestroy()");
        super.onDestroy();
    }

    /**
     * Interface method called by the usdtv framework on registering the current object
     * with it.
     * 
     * @param progress an integer less than 100
     * @param chNum currently scanned channel number
     * @param numOfServices number of services found on the current frequency
     * @param curFrequency current frequency being scanned
     * @param searchType digital or analog search type currently being performed
     * @param searchMessage any additional info about scanning
     */
    /*@Override
    public void scanStatusUpdate(final int progress, final int chNum, final int numOfServices,
            final int curFrequency,
            final int searchType, final int searchMessage) {
        
    	MyLog.d(TAG,"scanStatusUpdate progress="+progress);
        if (searchType == ChannelSearchType.SEARCH_ANALOG.ordinal()) {
            if (numOfServices > 0)
                mNumAnalogChannel = numOfServices;
            MyLog.d(TAG, "Search Type is Analog");

        } else if (searchType == ChannelSearchType.SEARCH_DIGITAL.ordinal()) {
            if (numOfServices > 0)
                mNumDigitalChannel = numOfServices;
            MyLog.d(TAG, "Search Type is Digital");

        } else {
        	MyLog.d(TAG, "Search Type is Invalid");
        }
        
        mScanHandler.post(new Runnable() {

            @Override
            public void run() {
                Log.d(TAG, "Handle Message..................");
                final float currentFrequency = (float) (curFrequency / 1000000.0);
                String strFrequency = ((Float) currentFrequency).toString();
                if (curFrequency == 0 && mTunerMode == InputSourceType.CABLE_INPUT
                        && searchType == ChannelSearchType.SEARCH_ANALOG.ordinal()) {
                    strFrequency = CABLE_ANALOG_FREQ;
                } else if (curFrequency == 0 && mTunerMode == InputSourceType.CABLE_INPUT
                        && searchType == ChannelSearchType.SEARCH_DIGITAL.ordinal()) {
                    strFrequency = CABLE_DIGITAL_FREQ;
                }

                if (searchMessage != ScanStatus.SCAN_FINISHED.ordinal()) {
                    if (progress >= SCAN_HALF_PERCENT
                            && !(mHeaderTextView.getText().equals(mRes.getString(R.string.ANALOG_AUTO_SCAN)))
                            && searchType == ChannelSearchType.SEARCH_ANALOG.ordinal()) {
                        mHeaderTextView.setText(R.string.ANALOG_AUTO_SCAN);
                    } else if (progress < SCAN_HALF_PERCENT
                            && !mHeaderTextView.getText().equals(mRes.getString(R.string.DIGITAL_AUTO_SCAN))
                            && searchType == ChannelSearchType.SEARCH_DIGITAL.ordinal()) {
                        mHeaderTextView.setText(R.string.DIGITAL_AUTO_SCAN);
                    }
                    
                    updateScanStatusText(chNum, strFrequency, mNumAnalogChannel, mNumDigitalChannel, progress);                    
                } else {
                    sendDisabledKeyBroadcast(false);

                    Wrapper.getWrapperInstance().updateChanneListToGTVDb(0);
					
                    mHeaderTextView.setText(R.string.AUTOSCAN_COMPLETE);
                    updateScanStatusText(chNum, strFrequency, mNumAnalogChannel, mNumDigitalChannel, SCAN_COMPLETE_PERCENT);

                    scanFinished = true;
                    cleanup();
                    
                    if (mNumAnalogChannel == 0 && mNumDigitalChannel == 0) {
                        new ToastCreator(mContext, mRes.getString(R.string.no_service_found), R.drawable.info)
                                .showToast();
                    }                                        

                    setTimeOut(3000); // enable timeout after scan complete
                    startTimeOut();

                    if (isOOBE) {
                        mLiveTv.startCurrentSource(InputSourceType.NON_TV_INPUT.ordinal());
                        mTuner.setTunerMode(InputSourceType.NON_TV_INPUT, mContext);
                    }
                }
            }
        });
    }*/

    private void sendDisabledKeyBroadcast(boolean disabled) {
        Log.d(TAG, "sendDisabledKeyBroadcast disabled=" + disabled);
        Intent i = new Intent(TvIntents.ACTION_CHANNEL_SCAN_DISABLEDKEY);
        i.putExtra(TvIntents.EXTRA_DISABLE_KEY, disabled);
        mContext.sendBroadcast(i);

    }

    /**
     * This method is called for starting the scan process.
     */
    private void startScan() {
        
        // Make a call to start auto scan and catch the return value
        // listener to register to get the scan status updates
       /* final int rtnValue = mTuner.startFullScan(ChannelSearchType.SEARCH_DIGITAL_AND_ANALOG,
                mTunerMode, this, isOOBE);
        if (rtnValue != ErrorCodes.SUCCESS) {
            final String text = mRes.getString(R.string.AUTOSCAN_FAIL);
            final ToastCreator toast = new ToastCreator(mContext, text, R.drawable.info);
            toast.showToast();
            finish();
        } else {
            sendDisabledKeyBroadcast(true);
        }*/
    }
 
    /**
     * This method is called for stopping the scan process.
     */
    private void stopScan() {
        /*final int stpScan = mTuner.stopScan();
        if (stpScan != ErrorCodes.SUCCESS) {
            final String text = mRes.getString(R.string.STOP_AUTOSCAN_FAIL);
            final ToastCreator toast = new ToastCreator(mContext, text, R.drawable.info);
            toast.showToast();
            return;
        }*/
        // Display progress dialog to the user
        mDialog = ProgressDialog.show(this, "", mRes.getString(R.string.scan_wait));
        mDialog.setContentView(R.layout.progress_dialog_view);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
    }
    
    public boolean isChannelScaned() {
        if (mNumAnalogChannel > 0 || mNumDigitalChannel > 0) {
            return true;
        }
        return false;
    }
    
    /**
     * Called when a key was released and not handled by any of the views inside
     * of the activity.
     * 
     * @param keyCode integer for the corresponding key
     * @param event KeyEvent occured
     * @return boolean true if key is handled
     */
    @Override
	public boolean onKeyUp(final int keyCode, final KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK)
				&& mDialog == null) {
			Log.d(TAG, "keyCode = " + keyCode);
			if (!scanFinished) {
				stopScan();

				if (mRunnable2 != null) {
					mScanHandler.removeCallbacks(mRunnable2);
					finish();
				}

				if (isChannelScaned()) {
					//cancelReceiver(); // don't exit itself
					//WidgetManager.exitFromApp(getApplicationContext());//used for exit app(TVBaseDialog dispose it Setting not use)
				}

                /*if (isOOBE) {
                    mLiveTv.startCurrentSource(InputSourceType.NON_TV_INPUT.ordinal());
                    mTuner.setTunerMode(InputSourceType.NON_TV_INPUT, mContext);
                }*/
                return false;
            } else {
                MyLog.d(TAG, "scanFinished=" + scanFinished);
                finish();
            }
        }
        return true;
    }

    /**
     * Called when a key was pressed down and not handled by any of the views
     * inside of the activity
     * 
     * @param keyCode integer for the corresponding key
     * @param event KeyEvent occured
     * @return boolean true if key is handled
     */
    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
        // Check whether this is power key (check with unique/scan code)
        if (event.getScanCode() == POWER_KEY) {
            return super.onKeyUp(keyCode, event);
        }
        return true;
    }

    private void updateScanStatusText(final int chnum, final String freq, 
            final int numAnalog, final int numDigital, final int progress){
        String statusMessage1=chnum+"";
        String statusMessage2=freq + " " + mRes.getString(R.string.MHZ);
        String statusMessage3=numAnalog+"";
        String statusMessage4=numDigital+"";
        mScanStatus_tv1.setText(statusMessage1);
        mScanStatus_tv2.setText(statusMessage2);
        mScanStatus_tv3.setText(statusMessage3);
        mScanStatus_tv4.setText(statusMessage4);
        Log.e(TAG,"statusMessage="+statusMessage1+statusMessage2+statusMessage3+statusMessage4);
        
        mProgressTextView.setText("\0" + progress + "%");
        mProgressBar.setProgress(progress);
    }

    private void cleanup(){
        /* To Dismiss the dialog and removing it from the screen */
        if (mDialog != null) {
            mDialog.dismiss();
        }        
    }
  //add for clear favorite.db by libaocheng
    private void clearfavoritedata(){
    	ContentResolver resolver =getContentResolver();
    	Uri uri=Uri.parse("content://com.google.tv.player/favorites/1/channels");
    	//String selection = "channel";
        String where = "channel LIKE \"%tunerMode="+ tunerMode + "%\"";
        Cursor cursor=null;
        try {
        	final int delRows=resolver.delete(uri, where, null);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally{
    		if(cursor!=null){
    			cursor.close();
    		}
    	}
    }
}

